package com.lopo.in18;

import com.lopo.pagehelper.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
import java.util.Objects;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @Autowired
    private MessageSource messageSource;
    @Autowired
    private HttpServletRequest request;

    /**
     * 处理其他抛出的异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleException(Exception e) {
        log.warn(e.getMessage(), e);
//        return R.of("999999", getLocaleMessage("999999", "unknown exception", null));
        log.warn("\nBizException：{}", e.getMessage());
        final String localeMessage = this.getLocaleMessage(e.getMessage());

        return ResponseEntity.ok(Response.error(-1, localeMessage));
    }

    /**
     * 获取国际化异常信息
     *
     * @param message
     * @param params
     */
    private String getLocaleMessage(String message) {
        String language = request.getParameter("lang");
        Locale locale = Objects.nonNull(language) ? new Locale(language) : Locale.getDefault();
        try {
            return messageSource.getMessage(message, null, locale);
        } catch (Exception e) {
            log.warn("本地化异常消息发生异常: {}", message);
            return message;
        }
    }
}